#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <strings.h>

class InetAddr
{
private:
    void HostToNet()
    {
        bzero(&_addr,sizeof(_addr));
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
        inet_pton(AF_INET,_ip.c_str(),&_addr.sin_addr.s_addr);
    }
    void NetToHost()
    {
        _port=ntohs(_addr.sin_port);
        char buffer[64];
        inet_ntop(AF_INET,&_addr.sin_addr.s_addr,buffer,sizeof(buffer));
        _ip=buffer;
    }
public:
    // 主机地址转网络
    InetAddr(){}
    InetAddr(uint16_t port, std::string ip = "0.0.0.0")
        : _port(port), _ip(ip)
    {
        HostToNet();
    }
    // 网络地址转主机
    InetAddr(struct sockaddr_in&addr)
        :_addr(addr) 
    {
        NetToHost();
    }
    struct sockaddr*Addr()
    {
        return (struct sockaddr*)&_addr;
    }
    socklen_t Len()
    {
        return sizeof(_addr);
    }
    void Init(const struct sockaddr_in&addr)
    {
        _addr=addr;
        NetToHost();
    }
    ~InetAddr() {}
private:
    struct sockaddr_in _addr;
    uint16_t _port;
    std::string _ip;
};